<template>
    <div>
        <el-row :gutter="5">
            <el-col :span="7">
                <el-row>
                    <el-col>
                        <el-card>
                            <el-calendar>
                                <template #date-cell="{ data }">
                                    <div style="height: calc(100% + 16px);width: calc(100% + 16px);margin: -8px;" @click="changeDate(data)">
                                        <p :class="data.isSelected ? 'is-selected' : ''">
                                            {{ data.day.split('-').slice(1)[1] }}
                                            {{ data.isSelected ? '✔️' : '' }}
                                        </p>
                                    </div>
                                </template>
                            </el-calendar>
                        </el-card>
                    </el-col>
                </el-row>
                <br>
                <el-row>
                    <el-card style="width: 100%;">
                        <template #header>
                            <div class="card-header">

                                <span>填写{{ date + "的" }}日记</span>
                            </div>
                        </template>
                        <el-form :model="form" label-width="80px">
                            <el-form-item label="项目名称:">
                                <el-row style="width: 100%;">
                                    <el-col :span="20">
                                        <el-select v-model="form.projectId" filterable remote reserve-keyword
                                            placeholder="请选择项目" :remote-method="remoteMethod" :loading="loading"
                                            size="default" style="width: 100%;">
                                            <el-option v-for="item in projectlist" :key="item.id" :label="item.name"
                                                :value="item.id" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="4" style="text-align: center;line-height: 30px;text-align: right;">
                                        <el-button @click="openAddProject()" type="primary" link>新建项目</el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-form-item label="工作内容:">
                                <el-input v-model="form.dailyContent" :autosize="{ minRows: 4 }" type="textarea"
                                    size="default" placeholder="请填写今日工作内容" />
                            </el-form-item>
                            <el-row>
                                <el-col :span='10'>
                                    <el-form-item label="消耗时间:">
                                        <el-input  v-model="form.useTime" type="number" placeholder="请填写消耗时间"
                                            style="width: 60px;" />小时
                                    </el-form-item>
                                </el-col>
                                <el-col :span='14'>
                                    <el-form-item label="本任务需要研究:" label-width="140px">
                                        <el-tooltip class="box-item" effect="dark" content="这个任务我需要学习，可能消耗较多工时。"
                                            placement="top-start">
                                            <el-radio-group v-model="form.isStudy">
                                            <el-radio-button size="default" :label="true">是</el-radio-button>
                                            <el-radio-button size="default" :label="false">否</el-radio-button>
                                        </el-radio-group>
                                        </el-tooltip>
                                      
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <br>
                            <el-row>
                                <el-col :span="16">
                                    <el-form-item label="工作进度:">
                                        <div style="width: 90%;" class="progress" ref="processbarRef"
                                            @mousedown="onDragStart">
                                            <el-progress style="cursor: pointer" :show-text="false"
                                                :percentage="form.percent"></el-progress>
                                        </div>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-input-number v-model="form.percent" :min="0" :max="100"
                                        @change="handleChangepercent" />
                                </el-col>
                            </el-row>
                        </el-form>
                        <br>
                        <div class="bottom">
                            <el-row class="row-bg" justify="center">
                                <el-col :span="5">
                                    <el-button type="primary" size="default" @click="adddaily()">填写</el-button>
                                </el-col>
                                <el-col :span="5">
                                    <el-button size="default" @click="cancel">重置</el-button>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>
                </el-row>
            </el-col>
            <el-col :span="17">
                <el-card style="width: 100%;height: 100%;" class="full-table" shadow="hover">
                    <el-alert style="margin-bottom: 15px;" type="success" :closable="false">
                        <template #default>
                            <div style="font-size: 20px;">
                                {{ titleinfo }}
                            </div>
                        </template>
                    </el-alert>
                    <div class="tableDiv">
                        <el-table :data="state.dailylist" highlight-current-row @cell-click="cellClick" border v-loading="loading">
                            <el-table-column v-for="(item, index) in tableColumn" :key="index" :type="item.type"
                                :prop="item.prop" :align="item.align" :label="item.label" :width="item.width">

                                <template v-if="item.type != 'index'" #default="scope">
                                    <div class="startcalss" v-if="item.prop == 'workStartTime'">
                                        {{ scope.row[item.prop].slice(0, scope.row[item.prop].length - 8) }}
                                    </div>
                                    <el-input v-if="item.prop == 'dailyContent' && item.edit" ref="tableInput"
                                        :autosize="{ minRows: 4 }" type="textarea" placeholder="请填写今日工作内容"
                                        v-model="scope.row[item.prop]" @blur="removeClass(scope.row)"></el-input>
                                    <el-input-number style="width: 120px;"  v-if="item.prop == 'workUse' && item.edit"
                                        v-model="scope.row[item.prop]" :min="0" :max="24" @blur="removeClass(scope.row)" />
                                    <span v-if="item.prop != 'percent' && item.prop != 'opearte'">{{ scope.row[item.prop]
                                    }}</span>
                                    <div v-if="item.prop == 'percent'" style="display: flex;align-items: center;">
                                        <div style="width: 70%;margin-right: 10px;" @mousedown="onpreDragStart">
                                            <el-progress :id="scope.row['projectDailyId']" style="cursor: pointer"
                                                :show-text="false" :percentage="scope.row[item.prop]"></el-progress>
                                        </div>
                                        <el-input-number style=" display:block" v-model="scope.row[item.prop]"
                                            @change="removeClass(scope.row)" :min="0" :max="100" />
                                    </div>
                                    <div v-if="item.prop == 'ope'"
                                        style="display: flex;align-items: center;justify-content: center;">
                                        <div v-if="!scope.row['isAbondon']">
                                            <!-- <el-button icon="ele-Edit" size="small" text type="primary"
                                                @click="updaterow(scope.row)"> 保存 </el-button> -->
                                            <el-button size="small" text type="danger"
                                                @click="abondon(scope.row['projectDailyId'])"> 移除 </el-button>
                                        </div>
                                        <div v-else>
                                            该工作已被中止
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <el-pagination v-model:currentPage="state.tableParams.page"
                        v-model:page-size="state.tableParams.pageSize" :total="state.tableParams.total"
                        :page-sizes="[10, 20, 50, 100]" small background @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
                </el-card>
            </el-col>
        </el-row>
        <AddProject ref="addProjectRef" title="新增项目" @handleQuery="remoteMethod" />

    </div>
</template>

<script lang="ts" setup name="projectDaily">
import { onMounted, reactive, ref, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import commonFunction from '/@/utils/commonFunction';
import processbar from '/@/components/process_bar/index.vue'
import { GetOwnProjects } from '/@/api/business/project'
import { AddProjectDaily, GetProjectDaily, UpdateProjectDaily, AbondonProjectDaily } from '/@/api/business/projectDaily'
import { GetTodayTime } from '/@/api/business/ProjectWorker'
import { colunms } from './colunms'
import { replace } from 'lodash-es';
import AddProject from '/@/views/business/project/component/addProject.vue';


const processbarRef = ref<InstanceType<typeof processbar>>();
const addProjectRef = ref<InstanceType<typeof AddProject>>();

const { removeHtml } = commonFunction();
const date = ref(new Date().toLocaleDateString().replaceAll('/', '-'))
const loading = ref(false)
const projectlist = ref([] as Array<object>)
const isDragEnd = ref(false)
const tableColumn = ref(colunms)
const titleinfo = ref('');
const state = reactive({
    loading: false,
    queryParams: {
        name: undefined,
    },
    tableParams: {
        page: 1,
        pageSize: 20,
        total: 0 as any,
    },
    dailylist: [] as Array<Object>
    // editNoticeTitle: '',
});
const form = reactive({
    projectId: null,
    dailyContent: '',
    useTime: 0,
    percent: 100,
    isStudy: false,
})

onMounted(async () => {
    await initData();
});

// watch(date, async (newVal, oldVal) => {
//     debugger
//     await handleQuery()
// })

// 打开新增页面
const openAddProject = () => {
    addProjectRef.value?.openDialog({ type: 1 });
};
const initData = async () => {
    await handleQuery();
    await remoteMethod();
    await time();
}
///绑定给current绑定change事件


const time = async () => {
    const time = (await GetTodayTime()).data.result;
    if (time > 7) {
        titleinfo.value = '今日工时: ' + time + '小时，您今天加班' + (time - 7) + '小时，辛苦您了!';
    } else {
        titleinfo.value = '今日工时: ' + time + '小时,辛苦您了!';
    }
    console.log(time);
}
const remoteMethod = async (query: string) => {
    let param = {
        name: query
    }
    const res = await GetOwnProjects(param)
    projectlist.value = res.data.result ?? [];

}

const changeDate = async (data: any) => {
    date.value = data.day
    await handleQuery()

}
const cancel = async () => {
    form.dailyContent = '';
    form.isStudy = false;
    form.percent = 100;
    form.projectId = null;
    form.useTime = 0;
}

const handleChangepercent = async (value: number) => {
    processbarRef.value?.changemodelvalue(value);
}
const adddaily = async () => {
    if (!form.projectId) {
        ElMessage.warning('请先选择项目');
        return;
    }
    if(form.useTime == 0){
        form.percent = 0;
    }
    let param = Object.assign(form, { workStartTime: date });
    await AddProjectDaily(param);
    await handleQuery()
    await time();
    form.dailyContent = '';
    form.isStudy = false;
    form.percent = 100;
    form.useTime = 0;
}


const cellClick = async (row, column, cell, event) => {
    for (let i = 0; i < document.getElementsByClassName('current-cell').length; i++) {
        document.getElementsByClassName('current-cell')[i].classList.remove('current-cell');
    }
    cell.classList.add("current-cell");
}
const removeClass = async (row: any) => {
    updaterow(row);
    document.getElementsByClassName('current-cell')[0].classList.remove('current-cell');
    await time();

}

const updaterow = async (row: any) => {
    if (!row.id) {
        delete row.id
    }
    await UpdateProjectDaily(row);
    ElMessage.success('日志已更新');

    await handleQuery()
    await time();

}

const abondon = async (id: any) => {
    await AbondonProjectDaily(id)
    ElMessage.warning('工作已中止');

    await handleQuery()
    await time();
}

// 查询操作
const handleQuery = async () => {
    loading.value = true;
    let params = Object.assign(state.queryParams, { Date: date });
    const res = await GetProjectDaily(params);
    state.dailylist = res.data.result?.items ?? [];
    state.tableParams.total = res.data.result?.total;
    loading.value = false;
};
const onDragStart = async (event: any) => {
    const progressBox = processbarRef.value;
    const rect = progressBox.getBoundingClientRect();
    const width = rect.width;
    const offsetX = event.clientX - rect.left;
    let percentage = Math.round((offsetX / width) * 100);
    percentage = Math.max(0, Math.min(percentage, 100));
    form.percent = percentage;
};

const onpreDragStart = async (event: any) => {
    let progressBox = '';
    let target = event.target.parentNode;
    while (progressBox == '') {
        if (target.role) {
            progressBox = target.id;
        } else {
            target = target.parentNode;
        }
    }
    const rect = target.getBoundingClientRect();
    const width = rect.width;
    const offsetX = event.clientX - rect.left;
    let percentage = Math.round((offsetX / width) * 100);
    percentage = Math.max(0, Math.min(percentage, 100));
    let dailylist = state.dailylist.find(p => p.projectDailyId == progressBox);
    if (dailylist) {
        dailylist.percent = percentage;
    }
    removeClass(dailylist)
    // data = percentage;
};

// 重置操作
const resetQuery = () => {
    state.queryParams.name = undefined;
    handleQuery();
};




// 改变页面容量
const handleSizeChange = (val: number) => {
    state.tableParams.pageSize = val;
    handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
    state.tableParams.page = val;
    handleQuery();
};
</script>
<style scoped>
.el-calendar-day{
    padding: 0px;
}
.tableDiv .el-input {
    display: none;
}

.tableDiv .el-input-number {
    display: none;
}

.tableDiv .el-textarea {
    display: none;
}

.tableDiv .startcalss+span {
    display: none;
}

.current-cell .el-input {
    display: block;
}

.current-cell .el-input-number {
    display: block;
}

.current-cell .el-textarea {
    display: block;
}

.current-cell .el-input+span {
    display: none;
}

.current-cell .el-textarea+span {
    display: none;
}

.current-cell .el-input-number+span {
    display: none;
}
</style>
